package com.amanda.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.amanda.dao.PermissionDao;
import com.amanda.dao.RoleDao;
import com.amanda.dao.UserDao;
import com.amanda.pojo.Permission;
import com.amanda.pojo.Role;
import com.amanda.pojo.User;
import com.amanda.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

/**
 * @author amanda
 * @Description 用户-角色-权限
 */

@Transactional
@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService{
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    // 根据用户名查询数据库，获取用户信息和所关联的角色信息，同时查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        // 1.查询用户基本信息
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        // 2.根据用户id查询用户的角色信息
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            // 3.查询角色的权限信息
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            if(permissions != null && permissions.size() > 0) {
                role.setPermissions(permissions);
            }
        }
        user.setRoles(roles);
        return user;
    }
}
